import { Button, Form, Row, Space, theme, Input, Select, Col } from "antd";
import React, { useMemo, useState } from "react";
import { DownOutlined } from '@ant-design/icons';
import { FormattedMessage, useIntl } from "react-intl";


interface IAdvancedSearchProps<T={}> {
    initData?: T,
    fields: Admin.IAdvancedField[];
    collapse?: boolean;
    simpleModeFields?: number;
    onChange?: (values: T) => void;
}

const AdvancedSearchButton = ({form, finalCollapse, setExpand, expand, onSearch, onReset}: any) => {
    return (
        <div style={{ textAlign: 'right' }}>
            <Space size="small">
                <Button type="primary" htmlType="submit" onClick={()=>{
                    typeof onSearch === "function" && onSearch(form.getFieldsValue());
                }}>
                    <FormattedMessage id="admin.layout.form.search.confirm" defaultMessage={"Search"} />
                </Button>
                <Button
                    onClick={() => {
                        form.resetFields();
                        typeof onReset === "function" && onReset({});
                    }}
                >
                    <FormattedMessage id="admin.layout.form.search.clear" defaultMessage={"Clear"} />
                </Button>
                { finalCollapse && <a
                        style={{ fontSize: 12 }}
                        onClick={() => {
                            setExpand(!expand);
                        }}
                    >
                        <DownOutlined rotate={expand ? 180 : 0} /> 
                        <FormattedMessage id="admin.layout.form.search.collapse" defaultMessage={"Collapse"} />
                    </a>
                }
            </Space>
        </div>
    );
};

export const AdvancedSearch = ({ fields, collapse, simpleModeFields, onChange, initData }: IAdvancedSearchProps) => {
    const [form] = Form.useForm();
    const { token } = theme.useToken();
    const [ expand, setExpand ] = useState(collapse);
    const [ simpleModeFieldsValue ] = useState(simpleModeFields ?? 3);
    const formStyle: React.CSSProperties = {
        maxWidth: 'none',
        // background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        padding: 24,
    };
    const intl = useIntl();
    const defaultValues= useMemo(() => {
        const data: any = {};
        fields.forEach((item: any) => {
            data[item.name] = item.defaultValue
        });
        return {
            ...data,
            ...(initData || {})
        };
    }, [fields]);
    const onFinish = (values: any) => {
        //console.log('Received values of form: ', values);
    };
    const finalCollapse = useMemo(() => {
        return simpleModeFieldsValue < fields.length;
    }, [expand, simpleModeFieldsValue, fields]);
    const renderField = useMemo(() => {
        const maxLength = finalCollapse ? (
            expand ? fields.length : (fields.length > simpleModeFieldsValue ? simpleModeFieldsValue : fields.length)
            ) : fields.length;
        const finalFields: (Admin.IAdvancedField<any>[])[] = [];
        let size: number = 0;
        let rowFields: any[] = [];
        for(let i=0;i<maxLength;i++) {
            const curItem = fields[i];
            const currentSize = curItem.col ? curItem.col : (Math.ceil(24/simpleModeFieldsValue));
            if(size + currentSize > 24) {
                finalFields.push([...rowFields]);
                rowFields = [{...curItem, col: currentSize}];
                size = currentSize;
            } else {
                rowFields.push({...curItem, col: currentSize});
                size += currentSize;
            }
        }
        if(rowFields.length > 0) {
            finalFields.push([...rowFields]);
        }
        return finalFields;
    }, [expand, finalCollapse, fields, simpleModeFieldsValue]);
    const buttonInNewLine = useMemo(() => {
        // const perSize = Math.ceil(24/simpleModeFieldsValue);
        let firstLineSize = 0;
        renderField[0]?.forEach((item) => {
            firstLineSize += item.col || simpleModeFieldsValue;
        });
        return {
            isNewLine: renderField.length > 1 ? true : firstLineSize >= 24,
            colSize: 24 - firstLineSize
        }
    }, [renderField, finalCollapse]);

    return (
        <Form form={form} name="advanced_search" initialValues={defaultValues} style={formStyle} onFinish={onFinish}>
            {
                renderField.map((items,index) => {
                    return <Row gutter={24} key={index}>
                        {
                            items.map((item, sIndex) => {
                                return (<Col key={`${index}_${sIndex}`} span={item.col}>
                                    <Form.Item
                                        name={item.name}
                                        label={<FormattedMessage id={item.label} defaultMessage={item.label} />}
                                        labelCol={{
                                            span: 8
                                        }}
                                    >
                                        { item.type === "Input" && <Input type="text" placeholder={item.placeholder && intl.formatMessage({
                                            id: item.placeholder,
                                            defaultMessage: item.placeholder || ""
                                        })} {...(item.props||{})}/>}
                                        { item.type === "Select" && <Select options={item.data || []} placeholder={item.placeholder && intl.formatMessage({
                                            id: item.placeholder,
                                            defaultMessage: item.placeholder || ""
                                        })} {...(item.props||{})}/>}
                                    </Form.Item>
                                </Col>);
                            })
                        }
                        {
                            !buttonInNewLine.isNewLine && <Col span={buttonInNewLine.colSize}>
                                <AdvancedSearchButton
                                    form={form}
                                    finalCollapse={finalCollapse}
                                    setExpand={setExpand}
                                    expand={expand}
                                    onSearch={onChange}
                                    onReset={onChange}
                                />
                            </Col>
                        }
                    </Row>
                })
            }
            {
                buttonInNewLine.isNewLine && <AdvancedSearchButton 
                    form={form}
                    finalCollapse={finalCollapse}
                    setExpand={setExpand}
                    expand={expand}
                    onSearch={onChange}
                    onReset={onChange}
                />
            }
        </Form>
    );
};